import { message } from 'antd';
import { getCard } from '../../services/financial';

const defPage = { page: 1, pageSize: 10 };

export default {
    namespace: 'card',
    state: {
        data: [],
        pagination: { ...defPage },
        card: {},
        query: {
            payType: '',
            from: '',
            to: '',
        },
    },
    subscriptions: {
        setup(args) {
            const { dispatch, history } = args;
            history.listen(({ pathname, query: { userId, storeId } }) => {
                if (pathname === '/financial/card') {
                    dispatch({
                        type: 'init',
                        card: { userId, storeId },
                    });
                }
            });
        }
    },
    effects: {
        * init({ card }, { put }) {
            yield put({
                type: 'upState',
                payload: { card },
            });
            yield put({
                type: 'load',
            });
        },
        * load({ payload }, { put, call, select }) {
            const {
                card: { userId, storeId },
                pagination: { page, pageSize },
                query,
            } = yield select(({ card }) => card);
            const {
                data: { list: data, pageination: pagination, vip },
                code,
                err,
            } = yield call(
                getCard,
                { page, pageSize, ...query, ...payload, userId, storeId },
            );
            if (code === '0000') {
                yield put({
                    type: 'upState',
                    payload: { data, pagination, vip },
                });
            } else {
                message.warning(err);
            }
        },
        * reSearch({ query }, { put }) {
            yield put({
                type: 'upState',
                payload: { query },
            });
            yield put({
                type: 'load',
                payload: { ...defPage },
            });
        },
    },
    reducers: {
        upState(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
    }
};
